package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserSerivce;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user/passport")
public class UserApiController {
    @Resource
    private UserSerivce userSerivce;
    @Resource
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo){
        //1、校验用户名、密码是否空/空串，     提前校验防止进库浪费性能

        //2、登陆成功
        UserInfo userInfo1 = userSerivce.login(userInfo);
        Map map = new HashMap();//不给map泛型，影响编译，不影响性能
        if (userInfo1 != null) {//service返回非null
            map = new HashMap<>();
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            map.put("token",uuid);
            map.put("nickName",userInfo1.getNickName());//页面头展示昵称用

            //保存缓存，以用下次登录访问
            //根据已登录的token中获取的UUID进缓存查找用户id
            redisTemplate.opsForValue().set(uuid,userInfo1.getId().toString(),
                    RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);//设置过期时间，单位

            return Result.ok(map);//cookie任意可访问，所以仅存昵称，不存账户密码

        } else {//返回用户信息null，账户信息错误
            return Result.fail().message("用户名或密码不正确");
        }


    }

    //退出登录
    @GetMapping("logout")
    public Result logout(HttpServletRequest httpServletRequest){
        String token = httpServletRequest.getHeader("token");
        redisTemplate.delete(token);
        return Result.ok();
    }

    //获取用户地址
    @GetMapping("/userAddressList")
    public List<UserAddress> getUserAddressList(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        return userSerivce.userAddressList(userId);
    }
}
